package com.hzy.oplus.hook.utils;

import android.annotation.SuppressLint;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.hzy.oplus.hook.bean.LoginResult;

/**
 * Created by huzongyao on 2018/12/31.
 */

public class UserUtils {

    public static final String LOGIN_DATA_STRING = "LOGIN_DATA_STRING";
    public static final String LOGIN_PASS_CODE = "LOGIN_PASS_CODE";
    public static final String LOGIN_USER_NAME = "LOGIN_USER_NAME";

    public static void saveUserName(String name) {
        try {
            SPUtils.getInstance().put(LOGIN_USER_NAME, name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String loadUserName() {
        String ret = "";
        try {
            ret = SPUtils.getInstance().getString(LOGIN_USER_NAME, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static String getPassCode() {
        long passCode = 1L;
        try {
            passCode = SPUtils.getInstance().getLong(LOGIN_PASS_CODE, 1L);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getPassCode(passCode);
    }

    public static String fetchPassCode() {
        long passCode = 1L;
        try {
            passCode = SPUtils.getInstance().getLong(LOGIN_PASS_CODE, 1L);
            SPUtils.getInstance().put(LOGIN_PASS_CODE, passCode + 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getPassCode(passCode);
    }

    public static void saveLoginData(String userString) {
        SPUtils.getInstance().put(LOGIN_DATA_STRING, userString);
    }

    public static LoginResult loadLoginData() {
        String loginString = SPUtils.getInstance().getString(LOGIN_DATA_STRING);
        LoginResult result = null;
        try {
            if (!StringUtils.isTrimEmpty(loginString)) {
                result = JSON.parseObject(loginString, LoginResult.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static String getPassCode(long code) {
        @SuppressLint("DefaultLocale")
        String passCode = String.format("%08d", code);
        if (passCode.length() > 8) {
            passCode = passCode.substring(passCode.length() - 8);
        }
        return passCode;
    }
}
